<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import {
  borrowListApi,
  borrowApplyApi,
  borrowApproveApi,
  borrowRejectApi,
  borrowReturnApi
} from '@/api/borrow'
import { equipmentTypeListAllApi } from '@/api/equipment'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive, onMounted } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await borrowListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.totalCount
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const borrowStatusOptions = ref([
  {
    label: t('borrowTable.borrowStatusOptionApply'),
    value: 0
  },
  {
    label: t('borrowTable.borrowStatusOptionApproved'),
    value: 1
  },
  {
    label: t('borrowTable.borrowStatusOptionRejected'),
    value: 2
  },
  {
    label: t('borrowTable.borrowStatusOptionReturned'),
    value: 3
  }
])

// 这里定义一个 equipmentTypeOptions 的变量，用于存储 equipmentType 的选项，其值通过 equipmentTypeListAllApi 获取
const equipmentTypeOptions = ref<any[]>([])
// 这里定义一个函数，用于获取 equipmentType 的选项，并赋值给 equipmentTypeOptions
const fetchEquipmentTypeOptions = async () => {
  const res = await equipmentTypeListAllApi()
  equipmentTypeOptions.value = res.data.map((v: any) => ({
    label: v.equipmentTypeName,
    value: v.equipmentTypeId
  }))
}

onMounted(() => {
  fetchEquipmentTypeOptions()
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'username',
    label: t('borrowTable.username'),
    search: {
      hidden: false
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'userRealName',
    label: t('borrowTable.userRealName'),
    search: {
      hidden: false
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'equipmentTypeId',
    label: t('equipmentTable.equipmentTypeId'),
    table: {
      formatter: (row: any) => {
        const found = equipmentTypeOptions.value.find((item) => item.value === row.equipmentTypeId)
        return found?.label || row.equipmentTypeId
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: equipmentTypeOptions,
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: equipmentTypeOptions,
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    detail: {
      formatter: (row: any) => {
        const found = equipmentTypeOptions.value.find((item) => item.value === row)
        return found?.label || row
      }
    }
  },
  {
    field: 'equipmentName',
    label: t('borrowTable.equipmentName'),
    search: {
      hidden: true
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'brand',
    label: t('borrowTable.brand'),
    search: {
      hidden: true
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'model',
    label: t('borrowTable.model'),
    search: {
      hidden: true
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'borrowQuantity',
    label: t('borrowTable.borrowQuantity'),
    search: {
      hidden: true
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'preReturnTime',
    label: t('borrowTable.preReturnTime'),
    search: {
      hidden: true
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'borrowStatus',
    label: t('borrowTable.borrowStatus'),
    table: {
      formatter: (row: any) => {
        const found = borrowStatusOptions.value.find((item) => item.value === row.borrowStatus)
        return found?.label || row.borrowStatus
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: borrowStatusOptions,
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: borrowStatusOptions,
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    detail: {
      formatter: (row: any) => {
        const found = borrowStatusOptions.value.find((item) => item.value === row)
        return found?.label || row
      }
    }
  },
  {
    field: 'createTime',
    label: t('borrowTable.createTime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="info" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>

              {data.row.borrowStatus === 0 && (
                <>
                  <BaseButton type="primary" onClick={() => approveBorrow(data.row)}>
                    {t('borrowTable.approveBorrow')}
                  </BaseButton>
                  <BaseButton type="danger" onClick={() => rejectBorrow(data.row)}>
                    {t('borrowTable.rejectBorrow')}
                  </BaseButton>
                </>
              )}

              {data.row.borrowStatus === 1 && (
                <BaseButton type="success" onClick={() => returnBorrow(data.row)}>
                  {t('borrowTable.returnBorrow')}
                </BaseButton>
              )}
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const approveBorrow = async (row: TableData | null) => {
  // 审批通过
  console.log('approveBorrow|row=', row)
  const res = await borrowApproveApi(row)
    .catch(() => {})
    .finally(() => {
      saveLoading.value = false
    })
  if (res) {
    dialogVisible.value = false
    currentPage.value = 1
    getList()
  }
}

const rejectBorrow = async (row: TableData | null) => {
  // 审批拒绝
  console.log('rejectBorrow|row=', row)
  const res = await borrowRejectApi(row)
    .catch(() => {})
    .finally(() => {
      saveLoading.value = false
    })
  if (res) {
    dialogVisible.value = false
    currentPage.value = 1
    getList()
  }
}

const returnBorrow = async (row: TableData | null) => {
  // 归还
  console.log('returnBorrow|row=', row)
  const res = await borrowReturnApi(row)
    .catch(() => {})
    .finally(() => {
      saveLoading.value = false
    })
  if (res) {
    dialogVisible.value = false
    currentPage.value = 1
    getList()
  }
}

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    console.log('formData=', formData)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
